package com.xwsz.demo.utils;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpClientUtil {
	
	private HttpClientUtil(){}
	
	private static final String CODE = "UTF-8";

	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
	
	private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1800000)
            .setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();
	private static HttpClientUtil instance = null;

	public static HttpClientUtil getInstance() {
		if (instance == null) {
			instance = new HttpClientUtil();
		}
		return instance;
	}

	/**
	 * 发送 post请求
	 * 
	 * @param httpUrl
	 *            地址
	 */
	public static String sendHttpPost(String httpUrl) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		return sendHttp(null,httpPost);
	}

	/**
	 * 发送 post请求
	 * 
	 * @param httpUrl 地址
	 *     
	 * @param params 参数(格式:key1=value1&key2=value2)
	 * 
	 */
	public static String sendHttpPost(String httpUrl, String params) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		try {
			// 设置参数
			StringEntity stringEntity = new StringEntity(params, CODE);
			stringEntity.setContentType("text/xml");
			httpPost.setEntity(stringEntity);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return sendHttp(null,httpPost);
	}
	
	/**post请求，支持服务端返回内容gzip压缩
	 * @param httpUrl 地址
	 * @param params 参数(格式:key1=value1&key2=value2)
	 * @param acceptGzip
	 * @return
	 */
	public static String sendHttpPost(String httpUrl, String params, boolean acceptGzip) {
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		try {
			// 设置参数
			StringEntity stringEntity = new StringEntity(params, CODE);
			stringEntity.setContentType("text/xml;charset=UTF-8");
			httpPost.setEntity(stringEntity);
			if (acceptGzip) {
				httpPost.addHeader("Accept-Encoding", "gzip");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return sendHttp(null,httpPost);
	}
	
	

	/**
	 * 发送 get请求
	 * 
	 * @param httpUrl
	 */
	public static String sendHttpGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return sendHttp(httpGet,null);
	}

	   /**
     * 发送http请求
     *
     * @return
     */
    private static String sendHttp(HttpGet httpGet, HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = HttpClients.createDefault();//NOSONAR
            if(null != httpGet){
                httpGet.setConfig(requestConfig);
                // 执行请求
                response = httpClient.execute(httpGet);
            }else{
                httpPost.setConfig(requestConfig);
                // 执行请求
                response = httpClient.execute(httpPost);
            }
            entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        entity = new GzipDecompressingEntity(entity);
                    }
                }
            }
            responseContent = EntityUtils.toString(entity, CODE);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
      //  log.info("第三方返回:{}",responseContent);
        return responseContent;
    }
	
    /**
     * 发送 post请求
     * 
     * @param httpUrl 地址
     *     
     * 
     */
    public static String sendHttpPost(String httpUrl, String params,String contentType) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        try {
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, CODE);
            stringEntity.setContentType(contentType);
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return sendHttpPost(httpPost);
    }
    /**
     * 发送Post请求
     * 
     * @param httpPost
     * @return
     */
    private static String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = HttpClients.createDefault();//NOSONAR
            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        entity = new GzipDecompressingEntity(entity);
                    }
                }
            }
            responseContent = EntityUtils.toString(entity, CODE);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return responseContent;
    }
}